#include "queue.h"
#include <stdlib.h> //for malloc

struct queue_t{
	size_t size;
	size_t count;
	size_t in_index;
	size_t out_index;
	char *buffer;
};

queue_status_t queue_create(queue_t **queue,size_t size){
	queue_t *new_queue;
	new_queue = malloc(sizeof(queue_t)+size);
	if(new_queue == NULL){
		*queue = NULL;
		return QUEUE_MEM_ERR;
	}
	new_queue->size      = size;
	new_queue->count     = 0;
	new_queue->in_index  = 0;
	new_queue->out_index = 0;
	new_queue->buffer    = ((char *)new_queue)+sizeof(queue_t);
	*queue = new_queue;
	return QUEUE_OK;
}

queue_status_t queue_put(queue_t *this ,char c){
	if(queue_is_full(this)){
		return QUEUE_FULL;
	}
	this->buffer[this->in_index] = c;
	this->count++;
	this->in_index++;
	if(this->in_index == this->size){
		this->in_index = 0;
	}
	return QUEUE_OK;
}

queue_status_t queue_get(queue_t *this,char *c){
	if(queue_is_empty(this)){
		return QUEUE_EMPTY;
	}
	*c = this->buffer[this->out_index];
	this->count--;
	this->out_index++;
	if(this->out_index == this->size){
		this->out_index = 0;
	}
	return QUEUE_OK;
}

int queue_is_empty(queue_t *this){
	return this->count == 0;
}

int queue_is_full(queue_t *this){
	return this->count == this->size;
}

void queue_destroy(queue_t *this){
	free(this);
}
